package com.zitangkou.user.filter;

import com.zitangkou.common.global.ConstantValue;
import com.zitangkou.common.global.UserContent;
import com.zitangkou.user.local.UserThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Deng Ningning
 * @version 1.0
 * @date 2020/9/16 20:50
 */
public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (UserThreadLocal.getUserInfo() == null) {
            UserContent userContent = setUserInfo(request);
            UserThreadLocal.setUserInfo(userContent);
        }
        return true;
    }

    private UserContent setUserInfo(HttpServletRequest request) {
        UserContent userContent = new UserContent();
        userContent.setUserId((String) request.getAttribute(ConstantValue.USER_ID));
        userContent.setEnterpriseId((String) request.getAttribute(ConstantValue.ENTERPRISE_ID));
        return userContent;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.removeUserInfo();
    }
}
